package com.midcent.networklib.interfac;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.ext.tools.HttpTools;
import com.midcent.networklib.R;
import com.midcent.networklib.manager.HttpRequestNetManager;
import com.midcent.networklib.utils.logger.LogUtils;
import com.midcent.networklib.utils.network.NetUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;

import static android.R.attr.permission;

/**
 * Created by xiangke on 2016/1/15.
 */
public class HttpBaseRequest {

    protected WeakReference<Context> mContext;
    protected String baseurl = HttpRequestNetManager.getServerHost();
    protected JSONObject postpara = new JSONObject();
    protected String url = null;
    protected String TAG = this.getClass().getName();
    protected RequestListener requestlistener;
    protected String timestamp;


    public HttpBaseRequest(Context context) {
        this.mContext = new WeakReference<Context>(context);
        this.timestamp = Long.toString(System.currentTimeMillis());
        init();
    }

    public HttpBaseRequest(Context context, String purl) {
        this.mContext = new WeakReference<Context>(context);
        this.timestamp = Long.toString(System.currentTimeMillis());
        this.url = purl;
    }

    public void setRequestListener(RequestListener prequestlistener) {
        this.requestlistener = prequestlistener;
    }


    protected String getContentBody() {
        Log.e("ttt", url + ":" + postpara.toString());
        return postpara.toString();
    }

    public void post() {
        sendRequst(Request.Method.POST);
    }

    public void get() {
        sendRequst(Request.Method.GET);
    }

    private Context getContext() {
        return mContext == null ? null : mContext.get();
    }

    public void sendRequst(int method) {
        if (getContext() == null) {
            return;
        }
        if (!NetUtils.isConnected(getContext())) {
            callbackonError(null);
        } else {
            HttpTools httptool = new HttpTools(getContext());
            HttpJObjectRequest request = new HttpJObjectRequest(method, url, getContentBody(), new Response.Listener() {
                @Override
                public void onResponse(Object response) {
                    JSONObject resp = (JSONObject) response;
                    LogUtils.w(TAG, "Request " + url + "postpara=" + getContentBody() + "---" + response.toString());
                    if (resp.optInt("code") == 2000) {
                        //Login success
                        saveCache(url, getContentBody(), resp.toString());
                        Log.e(url, resp.toString());
                        JSONObject data = resp.optJSONObject("data");
                        if (data != null) {
                            onSuccessReponse(data);
                            if (requestlistener != null) {
                                requestlistener.onResultSuccess(data);
                            }

                        } else {
                            JSONArray datalist = resp.optJSONArray("data");
                            if (datalist != null) {
                                onSuccessReponse(data);
                                if (requestlistener != null) {
                                    requestlistener.onResultSuccess(datalist);
                                }

                            } else {
                                onSuccessReponse(response);
                                if (requestlistener != null) {
                                    requestlistener.onResultSuccess(response);
                                }

                            }


                        }
                    } else if (resp.optInt("errcode") == 40004) {
                        callbackonError(resp);
                        getContext().sendBroadcast(new Intent("com.wnb.mall.action.TOKENINVALIDATE"));
                    } else {
                        callbackonError(resp);
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    callbackonError(null);
                }
            });
            request.setTimestamp(timestamp);
            httptool.sendRequest(request);
        }
    }


    public void saveCache(String url, String para, String response) {
        if (getContext() == null) {
            return;
        }
        boolean permission = (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
                && getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        if (permission) {
            LRUCacheManager.getInstance().put(url, para, response);
        }
    }

    public void callbackonError(JSONObject res) {
        if (getContext() == null) {
            return;
        }
        String response = null;
        boolean permission = (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
                && getContext().checkCallingOrSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        if (permission) {
            response = LRUCacheManager.getInstance().get(url, getContentBody());
        }

        JSONObject data = null;
        if (response != null) {
            try {
                JSONObject resp = new JSONObject(response);
                if (resp.optInt("errcode") == 0) {
                    data = resp.optJSONObject("data");
                    if (data == null) {
                        data = resp;
                    }
                }
            } catch (JSONException e) {
                data = null;
                e.printStackTrace();
            }
        }

        if (data != null) {
            onSuccessReponse(data);
            if (requestlistener != null) {
                requestlistener.onResultSuccess(data);
            }
        } else {
            if (requestlistener != null) {
                requestlistener.onError("网络连接失败，请稍后再试！");
            }
            onErrorReponse(getContext().getResources().getString(R.string.server_connect_failed), getContext().getResources().getString(R.string.server_connect_failed));
        }
    }

    public void init() {
    }

    public void onSuccessReponse(Object response) {
    }

    public void onErrorReponse(String errormsg, String errtype) {
    }
}
